package com.kh.pajx.sop.view.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kh.pajx.sop.base.ModelDrivenBaseAction;
import com.kh.pajx.sop.domain.HsNotice;
import com.kh.pajx.sop.domain.SysDepartment;
import com.kh.pajx.sop.domain.SysInsideUser;
import com.kh.pajx.sop.util.common.DwzAjaxResult;
import com.kh.pajx.sop.util.common.FormatDate;
import com.kh.pajx.sop.util.common.ValidatorUtils;
import com.opensymphony.xwork2.ActionContext;

/**
 * 公告管理Action
 * @author mxl
 * @createDate 2015年2月27日 下午4:37:52
 */
@Controller
@Scope("prototype")
public class HsNoticeAction extends ModelDrivenBaseAction<HsNotice>{
	private File filedata;
	private String filedataContentType;  
    private String filedataFileName;  
    private String err;  
    private String msg;  
    private String message;  
    private String fileExt = "jpg,jpeg,gif,bmp,png";
    
    
    /**公告类型*/
    private String noticeType;
    /**选择的部门编号*/
    private String deptCode;
    /**用来表示页面接收人类型*/
    private String recUser;
	
	/**公告列表*/
	public String list(){
		try {
			
			ActionContext.getContext().put("title",model.getTitle());
			hsNoticeService.findNoticeList(model, getPageNum(), getNumPerPage());
		} catch (Exception e) {
			e.printStackTrace();
			ActionContext.getContext().put("errorMsg", "检索失败！"+e.getMessage());
		}
		return "list";
	}
	
	/**添加公告页面*/
	public String addUi(){
		// 准备部门信息
		List<SysDepartment> departmentList = sysDepartmentService.getAll();
		ActionContext.getContext().put("departmentList", departmentList);
		return "addUi";
	}
	
	/**添加公告*/
	public void add(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		HttpServletRequest request = ServletActionContext.getRequest();
		System.out.println("通知内容：》》》"+model.getContent());
		try {
			if(!ValidatorUtils.validateFixedLengthNumber(model.getType(),1, false)){
	    		throw new Exception("属性[类型]输入错误，非法提交！");
	    	}
			if(!ValidatorUtils.validateNumber(model.getSubclass(), 2, false)){
	    		throw new Exception("属性[子类]输入错误，非法提交！");
	    	}
			if(!ValidatorUtils.validateRelativeSafeString(model.getTitle(),100, false)){
	    		throw new Exception("属性[标题]输入错误，非法提交！");
	    	}
			/*if(!ValidatorUtils.validateRelativeSafeString(model.getContent(),500, false)){
	    		throw new Exception("属性[内容]输入错误，非法提交！");
	    	}*/
			if("all".equals(recUser)){
				model.setReceiveUser("");
			}
			if("dept".equals(recUser)){
				model.setReceiveUser(request.getParameter("rusertwo"));
			}
			if("person".equals(recUser)){
				model.setReceiveUser(request.getParameter("ruserthree"));
			}
			model.setType(model.getType());
			model.setSubclass(model.getSubclass());
			model.setTitle(StringUtils.trim(model.getTitle()));
			model.setContent(StringUtils.trim(model.getContent()));
			model.setIsSend("0");//发送状态默认为0
			model.setCreateOperUser(getCurrentUser().getUserId());
			model.setCreateTime(FormatDate.dateTimeDetail());
			
			hsNoticeService.save(model);
			dwz.setMessage("保存成功！");
			dwz.setCallbackType("closeCurrent");
			dwz.setNavTabId("notice_list");
			dwz.setStatusCode("200");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			
			e.printStackTrace();
			dwz.setMessage("保存失败！<br>错误信息：" + e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}
	
	/**修改公告页面*/
	public String editUi(){
		// 准备部门信息
		List<SysDepartment> departmentList = sysDepartmentService.getAll();
		ActionContext.getContext().put("departmentList", departmentList);
		
		HsNotice notice=hsNoticeService.getById(StringUtils.trim(model.getUuid()));
		ActionContext.getContext().getValueStack().push(notice);
		return "editUi";
	}
	
	/**修改公告*/
	public void edit(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		HttpServletRequest request = ServletActionContext.getRequest();
		try {
			if(!ValidatorUtils.validateFixedLengthNumber(model.getType(),1, false)){
	    		throw new Exception("属性[类型]输入错误，非法提交！");
	    	}
			if(!ValidatorUtils.validateNumber(model.getSubclass(), 2, false)){
	    		throw new Exception("属性[子类]输入错误，非法提交！");
	    	}
			if(!ValidatorUtils.validateUUID(model.getUuid(),false)){
	    		throw new Exception("属性[公告主键]输入错误，非法提交！");
	    	}
			if(!ValidatorUtils.validateRelativeSafeString(model.getTitle(),100, false)){
	    		throw new Exception("属性[标题]输入错误，非法提交！");
	    	}
			/*if(!ValidatorUtils.validateRelativeSafeString(model.getContent(),500, false)){
	    		throw new Exception("属性[内容]输入错误，非法提交！");
	    	}*/
			HsNotice notice=hsNoticeService.getById(StringUtils.trim(model.getUuid()));
			notice.setTitle(model.getTitle());
			notice.setContent(model.getContent());
			notice.setType(model.getType());
			notice.setSubclass(model.getSubclass());
			if("all".equals(recUser)){
				notice.setReceiveUser("");
			}
			if("dept".equals(recUser)){
				notice.setReceiveUser(request.getParameter("rusertwo"));
			}
			if("person".equals(recUser)){
				notice.setReceiveUser(request.getParameter("ruserthree"));
			}
			
			hsNoticeService.update(notice);
			dwz.setMessage("修改成功！");
			dwz.setCallbackType("closeCurrent");
			dwz.setNavTabId("notice_list");
			dwz.setStatusCode("200");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("修改失败！<br>错误信息：" + e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
		
		
	}
	
	/**查看公告*/
	public String show(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			if(!ValidatorUtils.validateUUID(model.getUuid(),false)){
	    		throw new Exception("属性[公告主键]输入错误，非法提交！");
	    	}
			HsNotice notice=hsNoticeService.getById(StringUtils.trim(model.getUuid()));
			ActionContext.getContext().getValueStack().push(notice);
			return "show";
		} catch (Exception e) {
			
			e.printStackTrace();
			dwz.setStatusCode("300");
		    dwz.setConfirmMsg("查询错误" + e.getMessage());
		    DwzAjaxResult.josnMessage(dwz);
		    return null;
		}
		
	}
	
	/**使用 xheditor编辑器上传图片
	 * @throws IOException */
	public String imgUpload() throws IOException{
		
		String saveRealFilePath = ServletActionContext.getServletContext().getRealPath("/") + "XheditorUpload/" ;  
        File fileDir = new File(saveRealFilePath);  
        if (!fileDir.exists()) {  
            fileDir.mkdirs();  
        }  
        //设置上传文件的名称
        String newFileName=UUID.randomUUID().toString()+filedataFileName.substring(filedataFileName.lastIndexOf("."));
        File savefile= new File(saveRealFilePath + newFileName);  
        FileUtils.copyFile(filedata,savefile);  
        msg = "XheditorUpload/" + newFileName;  
        err="";  
        printInfo( err, msg);  
        ActionContext.getContext().put("message",message);
        System.out.println("msg:>>"+msg+"   message:>>>>"+message);
        return "succ";
		 
	}
	public void printInfo(String err,String newFileName) {  
        message = "{\"err\":\"" + err + "\",\"msg\":\"" + newFileName  
                        + "\"}";  
    }
	/**获取子类别*/
	public void getSubclass(){
		String jsonStr="";
		if("1".equals(noticeType)){
			jsonStr +="[\"\", \"---请选择---\"]";
			jsonStr +=",[\"1\", \"系统通知\"]";
		}else if("2".equals(noticeType)){
			jsonStr +="[\"\", \"---请选择---\"]";
			jsonStr +=",[\"1\", \"补卡流程\"]";
		}else if("3".equals(noticeType)){
			jsonStr +="[\"\", \"---请选择---\"]";
			jsonStr +=",[\"1\", \"快递通知\"]";
		}else{
			jsonStr +="[\"\", \"---请选择---\"]";
		}
		jsonStr = "[" + jsonStr + "]";
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");  
		response.setCharacterEncoding("utf-8");
        PrintWriter out = null;  
        try {
			out = response.getWriter();  
			out.println(jsonStr);  
		} catch (IOException e) {
			e.printStackTrace();
		}  
        out.flush();  
		out.close();
	}
	/**根据部门获取内部用户*/
	public String getInsideUserByDept(){
		List<SysInsideUser> suList=sysInsideUserService.getUserByDeptCode(deptCode);
		ActionContext.getContext().put("suList",suList);
		return "getInUser";
	}
	
	
	
	public File getFiledata() {
		return filedata;
	}

	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}

	public String getFiledataContentType() {
		return filedataContentType;
	}

	public void setFiledataContentType(String filedataContentType) {
		this.filedataContentType = filedataContentType;
	}

	public String getFiledataFileName() {
		return filedataFileName;
	}

	public void setFiledataFileName(String filedataFileName) {
		this.filedataFileName = filedataFileName;
	}

	public String getErr() {
		return err;
	}

	public void setErr(String err) {
		this.err = err;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getFileExt() {
		return fileExt;
	}

	public void setFileExt(String fileExt) {
		this.fileExt = fileExt;
	}

	public String getNoticeType() {
		return noticeType;
	}

	public void setNoticeType(String noticeType) {
		this.noticeType = noticeType;
	}

	public String getDeptCode() {
		return deptCode;
	}

	public void setDeptCode(String deptCode) {
		this.deptCode = deptCode;
	}

	public String getRecUser() {
		return recUser;
	}

	public void setRecUser(String recUser) {
		this.recUser = recUser;
	}
	
	
}
